<?php

declare(strict_types=1);

namespace App\Middleware\Auth;

use App\Services\loginServices;
use Hyperf\Utils\Context;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Hyperf\HttpServer\Contract\RequestInterface;

class FooMiddleware implements MiddlewareInterface
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var RequestInterface
     */
    protected $request;

    /**
     * @var HttpResponse
     */
    protected $response;

    public function __construct(ContainerInterface $container, HttpResponse $response, RequestInterface $request)
    {
        $this->container = $container;
        $this->response = $response;
        $this->request = $request;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        // 根据具体业务判断逻辑走向，这里假设用户携带的token有效

        $token = "";
        $header = $request->getHeaders();
        $isValidToken = true;
        if (!isset($header["authorization"]) && empty($header["authorization"])) {
            $querm = $request->getQueryParams();
            if (isset($querm["token"])){
                $token = $querm["token"];
            } else {
                $isValidToken = false;
            }

        } else {
            $token = $header["authorization"][0];
        }

        if (!empty($token)) {
            $token = urlencode($token);
            $user = loginServices::getUserInfo($token);

            if (!$user) {
                $isValidToken = false;
            } else {
                Context::set('user', $user);
            }
        }

        if ($isValidToken) {
            return $handler->handle($request);
        }

        return $this->response->json(
            [
                'code' => -1,
                'data' => [
                    'error' => '验证token无效，请重新登录',
                ],
            ]
        );
    }
}